package com.huluobo.a2204monthdemo.detail

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import com.blankj.utilcode.util.ToastUtils
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.google.android.material.tabs.TabLayout.Tab
import com.huluobo.a2204monthdemo.R
import com.huluobo.a2204monthdemo.adapter.CommonPagerAdapter
import com.huluobo.a2204monthdemo.databinding.ActivityDetailBinding
import com.huluobo.base.net.Const
import com.huluobo.base.view.BaseMVVMActivity

class DetailActivity : BaseMVVMActivity<ActivityDetailBinding, DetailViewModel>() {
    private var goodsId = 0
    private lateinit var commonPagerAdapter: CommonPagerAdapter
    private val fragment = mutableListOf<Fragment>()
    private val tabEntitys = arrayListOf<CustomTabEntity>()
    override fun initData() {
        goodsId = intent.getIntExtra(Const.PARAM_GOODS_ID, 0)
        viewModel.getGoodsDetail(goodsId)

        viewModel.getGoodsDetailSuccess.observe(this) {
            if (it.code == 200) {
                dataBinding.goods = it.data
                viewModel.goodsBean.postValue(it.data)
            } else {
                ToastUtils.showLong(it.message)
            }
        }

        viewModel.getGoodsDetailFailed.observe(this) {
            Log.i("TagA", "获取详情数据失败:$it")
        }
    }

    override fun initView() {
        tabEntitys.clear()
        tabEntitys.add(TabEntity("详情"))
        tabEntitys.add(TabEntity("评论"))
        dataBinding.detailTabLayout.setTabData(tabEntitys)

        fragment.clear()
        fragment.add(DetailFragment())
        fragment.add(CommentFragment())

        commonPagerAdapter = CommonPagerAdapter(this, fragment)
        dataBinding.detailVp2.adapter = commonPagerAdapter

        dataBinding.detailTabLayout.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                dataBinding.detailVp2.currentItem = position
            }

            override fun onTabReselect(position: Int) {
            }
        })

        dataBinding.detailVp2.registerOnPageChangeCallback(object : OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                dataBinding.detailTabLayout.currentTab = position
            }
        })
    }

    override fun getViewModel(): Class<DetailViewModel> {
        return DetailViewModel::class.java
    }

    override fun getLayoutId(): Int = R.layout.activity_detail
}